//
//  RACCommand+ML.m
//  hehe
//
//  Created by Robin on 16/2/26.
//  Copyright © 2016年 HolyShit. All rights reserved.
//


//#import <ReactiveCocoa/RACSubject.h>
#import "RACCommand+MY.h"
#import "RACSignal+Operations.h"
#import <objc/runtime.h>

@implementation RACCommand (MY_Private)

static char *cancleSubjectKey;

- (void)setCancleSubject:(RACSubject *)cancelSubject
{
    objc_setAssociatedObject(self, cancleSubjectKey, cancelSubject, OBJC_ASSOCIATION_RETAIN);
}

- (RACSubject *)cancleSubject
{
    return objc_getAssociatedObject(self, cancleSubjectKey);
}

@end

@implementation RACCommand (MY)

- (BOOL)isExecuting
{
    return [self.executing.first boolValue];
}

+ (instancetype)commandWithSignalBlock:(RACSignal *(^)(id input))signalBlock
{
    return [self commandWithEnabledSignal:nil signalBlock:signalBlock];
}

+ (instancetype)commandWithEnabledSignal:(RACSignal *)enabledSignal signalBlock:(RACSignal *(^)(id input))signalBlock
{
    __block RACCommand *command = [[self alloc] initWithEnabled:enabledSignal signalBlock:^RACSignal *(id input) {
        RACSignal *racSignal = signalBlock(input);
        [command cancle];
        return [racSignal takeUntil:command.cancleSubject];
    }];
    return command;
}


- (void)cancle
{
    if (!self.cancleSubject)
    {
        self.cancleSubject = [RACSubject subject];
    }
    [self.cancleSubject sendNext:@"cancel"];
}

@end
